<?php

class LinksController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='application.modules.admin.views.layouts.default';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index', 'view', 'create','update','links','iteminfo'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->blankLayout();
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Links;

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		if(isset($_POST['Links']))
		{
			
			
			$item = Links::model()->find(array(
				'condtion'=>'link_name = :link_name',
				'params'=>array(
					':link_name'=>$_POST['Links']['link_name']
				)
			));
			
			if ($item){
				die("exist");
			}else{
				$model->attributes=$_POST['Links'];
				
//				UtilTools::dump($model->attributes);
				
				if($model->save())
					die("ok");				
			}
			

		}
		
		$this->render('create',array(
			'model'=>$model,

		));
	}
	
	public function actionCreateAjax()
	{
		$model=new Links;

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		if(isset($_POST['Links']))
		{
//			UtilTools::dump($_POST);
//			echo $_POST['Links']['link_name'];
			
			$items = Links::model()->findAll('link_name = :link_name',array(
				':link_name'=>$_POST['Links']['link_name']
			));
			if($items)
			{
				die("exist");
			}
			else
			{
				$model->attributes = $_POST['Links'];
				if($model->save())
					die("ok");
			}
		}
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$this->baseLayout();
		
		$model=$this->loadModel($id);
		
	
		if(isset($_GET['status']))
		{
			$model->link_status = $_GET['status'];
			if ($model->save())
				die('ok');
		}
			

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		if(isset($_POST['Links']))
		{
// 			UtilTools::dump($_REQUEST);
			$model->attributes=$_POST['Links'];
			$model->link_status = $_POST['Links']['link_status'];
// 			UtilTools::dump($model->attributes);
// 			die();
			if($model->save())
				die("ok");
			else 
				die("false");
		}

		
		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	public function actionItemInfo($id)
	{
		$this->blankLayout();
		
		$model = $this->loadModel($id);
		
		$this->render('iteminfo',array(
			'data' => $model
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	/**
	* Deletes a particular model.
	* If deletion is successful, the browser will be redirected to the 'admin' page.
	* @param integer $id the ID of the model to be deleted
	*/
	public function actionAjaxDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			if($this->loadModel($id)->delete()){
				if(isset($_POST['ajax']) && $_POST['ajax'] == 1){
					echo "ok";
				}
	
			}
		}
		else
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	public function actionAjaxTrash($id){
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			$model->arc_state = Links::LINK_STATUS_TRASH;
	
			if($model->save()){
				if(isset($_POST['ajax']) && $_POST['ajax'] == 1){
					echo "ok";
				}
			}
		}
		else
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$criteria = new CDbCriteria(array(
			'condition'=>'link_status !=:link_status',
			'params'=>array(
				'link_status'=>Links::LINK_STATUS_TRASH
			)
		));
				
		$dataProvider=new CActiveDataProvider('Links',array(
			'criteria'=>$criteria
		));
		$this->render('index',array(
			'dataProvider' => $dataProvider,
			'model' => $model
		));
	}
	
	public function actionLinks()
	{
		$this->blankLayout();
		
		

		$state = isset($_REQUEST['cstatus'])?$_REQUEST['cstatus']:'';
		$ctype = $_REQUEST['ctype']!=''?$_REQUEST['ctype']:'';
		$page = $_REQUEST['cpage'] != 'undefined'?$_REQUEST['cpage']:10;
		
// 		$result = compact('state','ctype','page');
		
// 		UtilTools::dump($result);
		
//        $condition = 'arc_state != '.Article::STATUS_TRASH;
// 		$condition = 'link_status != '.Links::LINK_STATUS_TRASH;
// 		if(!empty($ctype))
// 			$condition .= ' AND link_type ='.$ctype;
// 		if(!empty($state))
// 			$condition .= ' AND link_status = '.$state;
		// $condition = 'arc_cid like %'.$category.
		//        if(!empty($ctype))
		//        	$condition .= ' AND arc_ctype = '.$ctype;
		

		
		$criteria = new CDbCriteria(array(
// 					'condition'=>$condition,
					'order'=>'link_id DESC',
		
		));
		
		if(!empty($ctype))
			$criteria->addCondtion('Link_type = '.$ctype);
		
		if(!empty($state))
			$criteria->addCondition('link_status = '.$state);
		
// 		UtilTools::dump($criteria);
		$dataProvider=new CActiveDataProvider('Links',array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>$page,
			),
		));
		

		
		$this->render('links',array(
			'dataProvider' => $dataProvider,
		));		
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Links('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Links']))
			$model->attributes=$_GET['Links'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Links::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='links-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	protected function blankLayout()
	{
		return $this->layout='application.modules.admin.views.layouts.blank';
	}
	
	protected function baseLayout()
	{
		return $this->layout='application.modules.admin.views.layouts.base';
	}
	

}
